import router from '@/router'
import { serialize } from '@/utils'
const { programmeFlag } = require('../../settings')

const state = {
  keepAliveList: [],
  queueList: [],
  showCrumbs: false
}

const mutations = {
  updateKeepAlive(state, to) {
    const name = to.meta.name || to.name
    if (to.meta.keepAlive && !state.keepAliveList.includes(name)) {
      state.keepAliveList.push(name)
    }
  },
  removeKeepAlive(state, name) {
    const i = this.keepAliveList.indexOf(name)
    if (i !== -1) {
      state.keepAliveList.splice(i, 1)
    }
  },
  updateQueueList(state, to) {
    if (to.meta.showCrumbs) { // 暂时这样做，不影响其他人
      state.showCrumbs = true
    }
    for (let i = 0; i < state.queueList.length; i++) {
      const item = state.queueList[i]
      if (item.name === to.name) {
        state.queueList.splice(i, state.queueList.length - i)
        break
      }
    }
    state.queueList.push({
      name: to.name,
      query: to.query,
      params: to.params,
      title: to.meta.title
    })
  }
}

function findMenu(menuList, path) {
  for (const m of menuList) {
    if ((m.url || '').replace(/\/+/g, '-') === (programmeFlag + path).replace(/\/+/g, '-')) {
      return m
    }
    if (m.childrens && m.childrens.length > 0) {
      const menu = findMenu(m.childrens, path)
      if (menu) {
        return menu
      }
    }
  }
  return null
}

const actions = {
  async goBack(ctx, step = -2) {
    const queueList = ctx.state.queueList
    if (queueList.length > -step) {
      return router.push(ctx.state.queueList[queueList.length + step])
    } else {
      return ctx.dispatch('goFirst')
    }
  },
  async goFirst({ state }) {
    if (state.queueList.length === 0) return
    return router.push(state.queueList[0])
  },
  async goPage(ctx, { path, query } = {}) {
    if (!path) return
    if (process.env.NODE_ENV === 'development') {
      router.push({
        path: path,
        query
      })
      return
    }
    const parent = window.parent.document
    if (!parent) return
    const app = parent.querySelector('#app')
    if (!app || !app.__vue__) return
    const menuTree = app.__vue__.$store.state.menu.menuTree
    const menu = findMenu(menuTree, path)
    if (!menu) return
    window.parent.postMessage({
      flag: 'addtag',
      extraData: {
        url: menu.url,
        title: menu.menuName,
        query: query ? '&' + serialize(query) : '',
        menuCode: menu.menuCode
      }
    }, '*')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
